<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
let users = []
// ----
const user = reactive({
  payId: 0,
  feeId: 'sponsorPush'
})
// ----
let curkey = 0
const cures = [{
  text: '待审核',
  type: 'get',
  url: 'meeting-organiser/index',
  data: {
    params: {
      'MeetingOrganiserSearch[status]': 0,
      // ----
      sort: 'SORT_DESC'
    }
  }
}, {
  text: '已审核',
  type: 'get',
  url: 'meeting-organiser/index',
  data: {
    params: {
      'MeetingOrganiserSearch[status]': 1,
      // ----
      sort: 'SORT_DESC'
    }
  }
}, {
  text: '已过期',
  type: 'get',
  url: 'meeting-organiser/index',
  data: {
    params: {
      'MeetingOrganiserSearch[status]': 2,
      // ----
      sort: 'SORT_DESC'
    }
  }
}]
// ----
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// ----
let menuIndex = 0
let menuSwiper = null
// ----
let forSortNum = 0
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const onSwiperMenu = (swiper) => { menuSwiper = swiper }
const initmenuSwiper = (index) => {
  if (Number(cures.length) === 0) return false
  // --初始化--
  menuSwiper.slides.forEach((current) => { current.classList.remove('active') })
  menuSwiper.slides[index].classList.add('active')
  menuSwiper.slideTo(index)
  // --点击slide事件--
  menuSwiper.on('tap', async () => {
    menuSwiper.slides.forEach((current) => { current.classList.remove('active') })
    menuSwiper.slides[menuSwiper.clickedIndex].classList.add('active')
    // ----
    proxy.$Myfun.setSearchRes(proxy, [menuSwiper.clickedIndex], ['curIndex', 'infoSch'], (result) => { forSearch.value = result })
  })
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取所有用户信息--
  await proxy.$http.get('dealer/index', {
    params: {
      page: 1,
      PageSize: 1000000000000
    }
  }).then((res) => {
    const userItems = []
    res.items.forEach((item, index) => {
      userItems.push({
        id: String(item.id),
        telphone: item.telphone,
        topupze: item.topupze
      })
    })
    users = userItems
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 5,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  const extra = {
    'MeetingOrganiserSearch[name]': infoSch.value,
    // ----
    page: page.num,
    PageSize: page.size
  }
  switch (String(cures[curkey].type)) {
    case 'post': {
      Object.assign(cures[curkey].data, extra)
      break
    }
    case 'get': {
      Object.assign(cures[curkey].data.params, extra)
      break
    }
  }
  // ----
  getListDataFromNet({
    forType: cures[curkey].type,
    forUrl: cures[curkey].url,
    forData: cures[curkey].data
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http[option.forType](option.forUrl, option.forData).then((res) => {
    switch (String(option.forType)) {
      case 'post': {
        if (res.success) {
          if (Number(pageNum) === 1 && Number(res.datainfo.length) > 0) forSortNum = res.datainfo[0].sort_num
          // ----
          successCallback && successCallback(res.datainfo)
        } else { errorCallback && errorCallback(res.message) }
        break
      }
      case 'get': {
        if (Number(pageNum) === 1 && Number(res.items.length) > 0) forSortNum = res.items[0].sort_num
        // ----
        successCallback && successCallback(res.items)
        break
      }
    }
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forUser = {}
    let forSponsorTime = ''
    users.some((theItem) => {
      if (String(theItem.id) === String(item.dealer_id)) forUser = theItem
    })
    await proxy.$Myfun.getJsonData(forUser.topupze, (resJson) => {
      resJson.some((oneItem) => {
        if (String(oneItem.id) === String(user.feeId)) {
          oneItem.info.some((twoItem) => {
            if (String(twoItem.id) === String(user.payId)) forSponsorTime = String(twoItem.endtime).split(' ')[0].replace(/-/g, '.')
          })
        }
      })
    })
    // ----
    let forImgs = []
    await proxy.$Myfun.getJsonData(item.ads_image, (resJson) => {
      if (Number(resJson.length) > 0) forImgs = resJson
    })
    // ----
    let forEwms = []
    await proxy.$Myfun.getJsonData(item.qrcode_image, (resJson) => {
      if (Number(resJson.length) > 0) forEwms = resJson
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      sponsorTime: forSponsorTime,
      imgs: forImgs,
      ewms: forEwms,
      status: item.status,
      isOpenExten: Number(item.status) === 1,
      // ----
      sortNum: forSortNum
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(1)
}
// ----
const getHeadFun = (type) => {
  switch (Number(type)) {
    case 1: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            // ----
            const opts = {
              region: proxy.$Global.aoss.region,
              bucket: proxy.$Global.aoss.bucket,
              accessKeyId: proxy.$Global.aoss.accessKeyId,
              accessKeySecret: proxy.$Global.aoss.accessKeySecret
            }
            if (Number(item.imgs.length) > 0) {
              const imgArr = item.imgs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            if (Number(item.ewms.length) > 0) {
              const imgArr = item.ewms
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            // ----
            await proxy.$http.delete('meeting-organiser/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 2: {
      proxy.$http.patch('meeting-organiser/update?id=' + item.id, {
        sort_num: Number(item.sortNum + 1),
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        mescroll.scrollTo(0)
        mescroll.resetUpScroll()
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
    case 3: {
      if (Number(item.status) === 2) return false
      // ----
      let forOpen = true
      let forCurState = 1
      if (item.isOpenExten) {
        forOpen = false
        forCurState = 0
      }
      // ----
      proxy.$http.patch('meeting-organiser/update?id=' + item.id, {
        status: forCurState,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        item.isOpenExten = forOpen
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  curkey = newVal.curIndex || 0
  infoSch.value = newVal.infoSch
  // --重新请求数据--
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  curkey = forSearch.value.curIndex || 0
  infoSch.value = forSearch.value.infoSch
})
onMounted(() => {
  getCurrencyInfo(() => {
    nextTick(() => { initmenuSwiper(curkey) })
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forCha xw-bgCL-11" v-if="Number(cures.length) > 0">
        <swiper class="FCA-menu" :slides-per-view="3" @swiper="onSwiperMenu">
          <swiper-slide v-for="(item, index) in cures"><div class="xw-flex"><p class="xw-anim xw-flex-W1 xw-flex xw-flex-center">{{item.text}}</p></div></swiper-slide>
        </swiper>
      </div>
      <!---->
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" placeholder="关键词找赞助商" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(1)">搜索</span>
        </div>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-plan xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LPN-title">{{item.name}}</div>
            <div class="LPN-work xw-color-13">赞助有效期：{{item.sponsorTime}}</div>
            <div class="LPN-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn xw-WBlue" @click="getAuditFun(1, item)">删除</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(2, item)">置顶</div>
              <div class="LPN-check xw-flex xw-flex-align">
                <span>审核</span>
                <div class="USS-check" @click="getAuditFun(3, item)"><input type="checkbox" class="a-switch" v-model="item.isOpenExten"/><label></label></div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-plan li { position: relative; margin: 1rem 1rem 0; padding: 0 1rem; overflow: hidden; }
.list-plan li:nth-of-type(1) { margin-top: 0; }
.LPN-title { padding: 1rem 0 0; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.LPN-work { padding: 0.5rem 0 0; }
.LPN-btns { padding: 1rem 0; overflow: visible; }
.LPN-check { overflow: visible; }
.LPN-check div { overflow: visible; }
</style>
